package com.ffcs.web.filter;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.log4j.NDC;
import org.springframework.util.Assert;

import com.ffcs.web.model.entity.WxUser;
import com.ffcs.web.utils.CommonConfig;
public class LogsFilter implements Filter {

	Logger logger = Logger.getLogger(LogsFilter.class);
	
	private static String appid = CommonConfig.getProperty("APPID");
	private static String appsecret = CommonConfig.getProperty("APPSECRET");
	private static String partner = CommonConfig.getProperty("PARTNER");
	//这个参数partnerkey是在商户后台配置的一个32位的key,微信商户平台-账户设置-安全设置-api安全
	private static String partnerkey = CommonConfig.getProperty("PARTNERKEY");
	//openId 是微信用户针对公众号的标识，授权的部分这里不解释
	//微信支付成功后通知地址 必须要求80端口并且地址不能带参数
	private static String notifyurl = CommonConfig.getProperty("NOTIFYURL");

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filter) throws IOException, ServletException {
		
		Assert.notNull(request);
		
		request.setCharacterEncoding("utf-8");
         //设置response字符编码
        response.setContentType("text/html;charset=utf-8");
		
		//打印请求日志方法
		String canShu=outLogs(request);
		
		
//		logger.info("请求参数canShu="+canShu);
		
		HttpServletRequest req=((HttpServletRequest) request);
		HttpServletResponse resp=((HttpServletResponse) response);
		String frontUrl=req.getRequestURL().toString();
		String flagUrl="http://localhost:8008";
		String flagUrl2="notifyurl";
		String flagUrl3="login.jsp";
		String flagUrl4="gotoMyCounse";
		String flagUrl5="jpg";
//		logger.info("处理前frontUrl==="+frontUrl);
		if(!frontUrl.contains(flagUrl2) && !frontUrl.contains(flagUrl3) && !frontUrl.contains(flagUrl4) && !frontUrl.contains(flagUrl5)){
//			logger.info("处理frontUrl是否含有"+frontUrl);
			if(frontUrl.contains(flagUrl)){
//				logger.info("处理frontUrl确定含有"+frontUrl);
				frontUrl=frontUrl.replace(flagUrl,CommonConfig.getProperty("BASE_URL"));
//				logger.info("处理后frontUrl==="+frontUrl);
			}
//			logger.info("user-session==="+req.getSession().getAttribute("wxUser"));
			if(null==req.getSession().getAttribute("wxUser") && !frontUrl.contains("commonRedirectUri")){
				String redirect_uri=CommonConfig.getProperty("COMMON_REDIRECT_URI");
				
				if(!canShu.equals("")){
					frontUrl=frontUrl+"?"+canShu;
				}
//				System.out.println("frontUrl="+frontUrl);
				frontUrl=URLEncoder.encode(frontUrl);
				System.out.println("url加密后frontUrl="+frontUrl);
				String url="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri="+redirect_uri+"&response_type=code&scope=snsapi_userinfo&state="+frontUrl+"#wechat_redirect";
//				System.out.println("重定向到"+url);
				resp.sendRedirect(url);
				return ;
			}
		}
		
		
		//在PC端测试用，PC端无法获取微信授权
//        WxUser wuser=new WxUser ();
//        wuser.setId(57);
//        wuser.setNickname("code");
//        wuser.setTelephone("");
//        wuser.setHeadimgurl("http://wx.qlogo.cn/mmopen/PiajxSqBRaEJ4AHPcp7kQVxCicqEmH6UHWW5bsFpPeQAaJTdia0ibiazpibIxw8XIQZAnkYCI8pdVHv8jYIsFHMUiaHicg/0");
//        ((HttpServletRequest) request).getSession().setAttribute("wxUser", wuser);
//        ((HttpServletRequest) request).getSession().setAttribute("cityName", "福州");
//        ((HttpServletRequest) request).getSession().setAttribute("counseTel", "18060479602");
        
        
		filter.doFilter(request, response);
		
		//清空log4j NDC
		NDC.clear();
	}

	/**
	 * @Title: outLogs 
	 * @Description: 打印请求日志方法
	 * @param :@param request
	 * @return void    返回类型  
	 * @author zhaoyingguang
	 * @date 2014年5月28日 下午2:39:20
	 */
	public String outLogs(ServletRequest request) {
		//打印请求日志
		StringBuilder requestParams = new StringBuilder("请求地址[url="+((HttpServletRequest) request).getRequestURL().toString()+"]的请求参数");
		StringBuilder requestParams2 = new StringBuilder("");
		String requestStr=((HttpServletRequest) request).getRequestURL().toString();
		String requestst[]=requestStr.split("\\/");
		if((!"getSession".equals(requestst[requestst.length-1])) 
				&& (!(requestst[requestst.length-1]).contains(".jsp"))
				&& (!(requestst[requestst.length-1]).contains(".png"))
				&& (!(requestst[requestst.length-1]).contains(".jpg"))
				&& (!(requestst[requestst.length-1]).contains(".css"))
				&& (!(requestst[requestst.length-1]).contains(".gif"))
				&& (!(requestst[requestst.length-1]).contains(".js"))){
			@SuppressWarnings("unchecked")
			Map<String, String[]> requestParameterMap= request.getParameterMap();
			for (Map.Entry<String, String[]> entry : requestParameterMap.entrySet()) {
				String values="";
				for(String value : entry.getValue()){
					values += value;
				}
				requestParams2.append(""+entry.getKey()+"="+values+"&");
			}
			logger.info(requestParams.toString()+requestParams2.toString());
			return requestParams2.toString()+"1=1";
		}
		return "";	
	}
	
	public void init(FilterConfig arg0) throws ServletException {
		
	}

	public LogsFilter() {
		super();
	}


	public void destroy() {
		
	}
}
